<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="shortcut icon" href="">
    <title>Life Of Game</title>
    <style type="text/css">
        body {
            background-color: #eccc68;
        }

        canvas {
            width: 400px;
            height: 300px;
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <script type="module">
        import {createCanvas, vector2, animation, mouse, curve, circle, rect, line, fill, stroke, frame} from './spring/board.js'
        import {Particle, Spring} from './spring/object.js'

        const width = 1200, height = 800, w = 10
        const cols = width / w, rows = height / w

        function createGrid(cols, rows) {
            let grid = new Array(cols)
            for (let i = 0 ; i < grid.length; ++i) {
                grid[i] = new Array(rows)
            }
            return grid
        }
        createCanvas(width / 2, height / 2)
        frame(10)
        let grid = createGrid(cols, rows)
        for (let i = 0; i < cols; ++i) {
            for (let j = 0; j < rows; ++j) {
                grid[i][j] = ~~(Math.random() * 2)
            }
        }
        function draw() {
            for (let i = 0; i < cols; ++i) {
                for (let j = 0; j < rows; ++j) {
                    if (grid[i][j] === 1) {
                        rect((i + 0.5) * w, (j + 0.5) * w, w, w)
                        fill("#fffc")
                    }
                }
            }
            let next = createGrid(cols, rows)

            for (let i = 0; i < cols; ++i) {
                for (let j = 0; j < rows; ++j) {
                    let state = grid[i][j]

                    let sum = 0
                    for (let x = i - 1; x < i + 2; ++x ) {
                        for (let y = j - 1; y < j + 2; ++y ) {
                            let x_ = (x + cols) % cols
                            let y_ = (y + rows) % rows
                            sum += grid[x_][y_]
                        }
                    }
                    sum -= grid[i][j]

                    let flag = 3
                    if (state === 0 && sum === flag) {
                        next[i][j] = 1
                    } else if (state === 1 && (sum < flag - 1 || sum > flag)) {
                        next[i][j] = 0
                    } else {
                        next[i][j] = state
                    }
                }
            }
            grid = next


        }
        animation(draw)
    </script>
</body>

</html>